package com.example.summer_pro.controller;

import com.example.summer_pro.entity.User;
import com.example.summer_pro.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
public class HomeController {
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Map<String, Object> registerNewUser(@RequestBody Map<String, String> remap){
        String name=remap.get("name");
        String password=remap.get("password");
        Map<String, Object> map=new HashMap<>();
        try{
            User user=new User(name,password);
            User user1=userService.selectUserByUsername(name);
            if(user1!=null){
                map.put("success",false);
                map.put("message","用户名已注册！");
            }else {
                userService.registerNewUser(user);
                map.put("success",true);
                map.put("message","注册成功! ");
            }
        }catch (Exception e){
            e.printStackTrace();
            map.put("success",false);
            map.put("message","注册失败！");
        }
        return map;
    }
    @PostMapping("/login")
    public Map<String, Object> loginUser(@RequestBody Map<String, String> remap, HttpServletRequest request) {
        //HttpSession session = request.getSession();
        String name = remap.get("name");
        String password = remap.get("password");
        Map<String, Object> map = new HashMap<>();
        try {
            User user = new User(name, password);
            User user1 = userService.selectUserByUsername(name);
            if (user1 == null) {
                map.put("success", false);
                map.put("message", "用户名输入错误");
            } else {
                if (!password.equals(user1.getPassword())) {
                    map.put("success", false);
                    map.put("message", "密码输入错误");
                } else {
                    request.getSession().setAttribute("name", name);
                    request.getSession().setAttribute("u_id", user1.getU_id());
                    map.put("success", true);
                    map.put("message", "登录成功");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", false);
            map.put("message", "用户登录失败！");
        }
        return map;
    }
}
